﻿using System;
using Foothill.Model;

namespace Foothill.Service.AdService
{
    public class YearStatsGroupManager : IStatsGroupManager
    {
        // determine group Id and name
        public Tuple<int, string> DetermineGroup(ForSaleAd post)
        {
            Tuple<int, string> result = new Tuple<int, string>((int)YearStatsGroups.MoreThanTenYears, "10年以上");

            int age = DateTime.Now.Year - post.YearMade;

            if (age < 1)
            {
                result = new Tuple<int, string>((int)YearStatsGroups.LessThanOneYear, "1年以下");
            }
            else if (age >= 1 && age < 2)
            {
                result = new Tuple<int, string>((int)YearStatsGroups.OneToTwoYears, "1年 到 2年");
            }
            else if (age >= 2 && age < 5)
            {
                result = new Tuple<int, string>((int)YearStatsGroups.TwoToFiveYears, "2年 到 5年");
            }
            else if (age >= 5 && age < 10)
            {
                result = new Tuple<int, string>((int)YearStatsGroups.FiveToTenYears, "5年 到 10年");
            }
            else
            {
                result = new Tuple<int, string>((int)YearStatsGroups.MoreThanTenYears, "10年以上");
            }

            return result;
        }

        public Func<ForSaleAd, bool> GetGroupFunc(int groupId)
        {
            Func<ForSaleAd, bool> func;
            YearStatsGroups yearAgeGroup = GetMileageStatsGroupEnum(groupId);

            int thisYear = DateTime.Now.Year;

            switch (yearAgeGroup)
            {
                case YearStatsGroups.LessThanOneYear:
                    func = c => thisYear - c.YearMade < 1;
                    break;
                case YearStatsGroups.OneToTwoYears:
                    func = c => (thisYear - c.YearMade >= 1) && (thisYear - c.YearMade < 2);
                    break;
                case YearStatsGroups.TwoToFiveYears:
                    func = c => (thisYear - c.YearMade >= 2) && (thisYear - c.YearMade < 5);
                    break;
                case YearStatsGroups.FiveToTenYears:
                    func = c => (thisYear - c.YearMade >= 5) && (thisYear - c.YearMade < 10);
                    break;
                default:
                    func = c => thisYear - c.YearMade >= 10;
                    break;
            }

            return func;
        }

        internal YearStatsGroups GetMileageStatsGroupEnum(int groupId)
        {
            YearStatsGroups yearAgeGroup = YearStatsGroups.FiveToTenYears;

            if (Enum.IsDefined(typeof(YearStatsGroups), groupId))
            {
                yearAgeGroup = (YearStatsGroups)groupId;
            }

            return yearAgeGroup;
        }
    }
}
